package com.uikoo9.manage.y.controller;

import com.jfinal.kit.JsonKit;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Logger;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.DbKit;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Record;
import com.uikoo9.manage.y.model.*;
import com.uikoo9.manage.y.util.*;
import com.uikoo9.plugin.QTree1;
import com.uikoo9.util.core.annotation.QControllerUrl;
import com.uikoo9.util.jfinal.QController;
import com.uikoo9.util.jfinal.ucenter.model.UcenterUserModel;
import com.uikoo9.util.plugin.json.QJsonUtil;
import org.junit.Test;


import java.util.*;

/**
 * YCommentController
 *
 * @author qiaowenbin
 */
@QControllerUrl("/y/c")
public class YreadyController extends YController {

    private static String pertab = "com.uikoo9.manage.y.model.";
    private static String endtab = "Model";

    public void yprojectlist(){
        Map _param = new HashMap();
        Integer _ptype = getParaToInt("ptype",-1);
        Map querytype = new HashMap();
        if(_ptype>=0){//这里vue写多了，项目列表在 ylayoutdata 已经根据类型分好了。正常无需ptype查询
            _param.put("y_project_type",_ptype);
            String[] ss = {"y_project_type"};
            querytype.put(SqlKit.EQUAL,ss);//如果 equal 可以不设置，传null
        }
        renderJson(YProjectModel.dao.findMyProject(querytype,_param));
    }

    public void ylayoutdata(){
        List<Record> projecttype = Db.find("select y_enum_val,y_enum_showname from t_y_enum where y_enum_name = 'y_project_type'");

        List<Record> list = YProjectModel.dao.findMyProject(null,null);
        Map<String ,List<Record>> typeProject = new HashMap<String, List<Record>>();
        for(Record r1:list){
            String _projecttype = r1.getInt("y_project_type")+"";
            List<Record> _pl = null;
            if(typeProject.get(_projecttype) == null){
                _pl = new ArrayList<Record>();
                typeProject.put(_projecttype,_pl);
            }else{
                _pl = typeProject.get(_projecttype);
            }
            _pl.add(r1);
        }

        for(Record record:projecttype){
            record.set("projectlist",typeProject.get(record.getStr("y_enum_val")));
        }

        Map result = new HashMap();
        result.put("projecttype",projecttype);

        Integer id = getParaToInt("id",0);
        result.put("quotes",YQuotesModel.dao.getNextQuotes(id));
        renderJson(result);
    }

    public void getQuotes(){
        Integer id = getParaToInt("id",0);
        Map result = new HashMap();
        result.put("quotes",YQuotesModel.dao.getNextQuotes(id));
        renderJson(result);
    }



    public void now() {
        Integer pid = getParaToInt("pid",-1);

        Map map = new HashMap();
        map.put("y_idea_level", -1);
//        map.put("y_idea_status",5);
        Map querytype = new HashMap();
        String[] ss = {"y_idea_status"};
        querytype.put(SqlKit.EMPTY, ss);


        Map<String, List<Map>> listmyulmap = new HashMap<String, List<Map>>();
        List<Map> ltabstype = new ArrayList<Map>();
        List<YEnumModel> listptype = YEnumModel.dao.findByName("y_project_type");
        for (YEnumModel ye : listptype) {
            Map a = new HashMap();
            String id = ye.getStr("y_enum_val") + "";
            a.put("id", id);
            a.put("text", ye.getStr("y_enum_showname"));
            ltabstype.add(a);

            List<Map> listmyul = new ArrayList<Map>();
            map.put("p.y_project_type", id);
            List<YIdeaModel> list = YIdeaModel.dao.find(querytype, map);
            for (YIdeaModel yp : list) {
                Map am = new HashMap();
                am.put("text", yp.getStr("y_idea_name"));
                am.put("id", "id" + yp.getInt("y_project_id") + "-" + yp.getInt("id"));
                am.put("status", yp.getInt("y_idea_status") == null ? 0 : yp.getInt("y_idea_status"));
                listmyul.add(am);
            }
            listmyulmap.put("listmyul" + id, listmyul);
        }
        setAttr("ltabstype", ltabstype);
        setAttr("listmyulmap", listmyulmap);


        List<Map> l = new ArrayList<Map>();
        for (int i = 1; i <= 5; i++) {
            Map a = new HashMap();
            String id = i + "";
            a.put("id", id);
            a.put("pid", --i + "");
            a.put("text", "菜单" + id);
            a.put("url", "/" + id);
            l.add(a);
            i++;
        }
        setAttr("tree", new QTree1(0, "/", "根菜单", l, null));


        List<Map> ltabs = new ArrayList<Map>();
        List<YProjectModel> listp = YProjectModel.dao.findAll();
        Map<String, QTree1> maptree = new HashMap();
        for (YProjectModel p : listp) {
            Map a = new HashMap();
            String id = p.getInt("id") + "";
            a.put("id", id);
            a.put("text", p.getStr("y_project_name"));
            ltabs.add(a);
            maptree.put("tree" + id, new QTree1(0, "/", p.getStr("y_project_name"),
                    null, "select a.id,a.y_idea_parentid pid," +
                    "a.y_idea_name text,a.y_project_id url  " +
                    "from t_y_idea a where 1=1 and a.y_project_id = " + id + " and a.y_idea_parentid = ?"));
            a.put("children",maptree.get("tree" + id).getChildren());
        }

        if(pid>0){
            Map result = new HashMap();
            result.put("maptree",ltabs);
            renderJson(result);
        }else {
            setAttr("maptree", maptree);
            setAttr("ltabs", ltabs);
            render("/WEB-INF/view/fore/y/y-now.html");
        }
    }

    public void teamline() {
        renderJson(YIdeaModel.dao.findTeamline());
    }

    public void plan() {
        Integer projectid = getParaToInt(0);
        Integer parentid = getParaToInt(1, 0);
        Integer pid = getParaToInt("pid",-1);
        Integer upid = getParaToInt("upid",0);
        if(projectid ==null){
            projectid = pid;
        }
        if(parentid == 0){
            parentid = upid;
        }

        Map m = new HashMap();
        m.put("a.y_project_id", projectid);
        m.put("a.y_idea_parentid", parentid);

        List<YIdeaModel> list = YIdeaModel.dao.findRelaProject(m);
        List<Map> listmyul = new ArrayList<Map>();
        List<Map> listmyul1 = new ArrayList<Map>();
        List<Map> listcoumentul = new ArrayList<Map>();
        for (YIdeaModel yp : list) {
            Map a = new HashMap();
            a.put("text", yp.getStr("y_idea_name"));
            a.put("id", yp.getInt("id"));
            a.put("status", yp.getInt("y_idea_status") == null ? 0 : yp.getInt("y_idea_status"));
            a.put("sort", yp.getInt("y_idea_sort"));
            Integer s = yp.getInt("y_idea_status");
            if (s != null && s == 10) {
                listmyul.add(a);
            } else {
                listmyul1.add(a);
                Map b = new HashMap();
                b.put("text", yp.getLong("commentcount"));
                b.put("id", yp.getInt("id"));
                listcoumentul.add(b);
            }
        }
        if(pid>0){
            Map result = new HashMap();
            result.put("listmyul1",listmyul1);
            result.put("plan",YIdeaModel.dao.findById(parentid));
            result.put("project",YProjectModel.dao.findById(projectid));
            renderJson(result);
        }else {
            setAttr("pid", projectid);
            setAttr("parentid", parentid);
            setAttr("plan", YIdeaModel.dao.findById(parentid));
            setAttr("project", YProjectModel.dao.findById(projectid));
            setAttr("listmyul", listmyul);
            setAttr("listmyultop", listmyul1);
            setAttr("listcoumentul", listcoumentul);
            for (int i = 1; i < 4; i++) {
                Map a = new HashMap();
                a.put("text", "&nbsp;&nbsp;&nbsp;");
                a.put("id", "id");
                listmyul1.add(a);
//            listcoumentul.add(a);
            }
            render("/WEB-INF/view/fore/y/y-plan.html");
        }
    }

    public void project() {
        List<Record> list = YProjectModel.dao.findMyProject(null,null);
        List<Map> listmyul = new ArrayList<Map>();
        for (Record yp : list) {
            Map a = new HashMap();
            a.put("text", yp.getStr("y_project_name"));
            boolean hasteam = StringUtil.isStrTrimEmpty(yp.getStr("y_team_name"));
            String sname = "-"+(hasteam ? yp.getStr("cuser_name") : yp.getStr("y_team_name") );
            a.put("extend",hasteam? sname :"<a href='/y/c/team/"+yp.getInt("y_team_id")+"' style='float:right;'>"+sname+"</a>" );
            a.put("sort", yp.getInt("y_project_sort"));
            a.put("id", "id" + yp.getInt("id"));
            listmyul.add(a);
        }
        for (int i = 1; i < 4; i++) {
            Map a = new HashMap();
            a.put("text", "&nbsp;&nbsp;&nbsp;");
            a.put("id", "id");
            listmyul.add(a);
        }
        setAttr("listmyul", listmyul);
        render("/WEB-INF/view/fore/y/y-project.html");
    }

    public void teamuser() {
        String _sql = "select c.y_team_name,a.* from t_y_teamruser a\n" +
                "  LEFT JOIN t_y_team c on a.y_team_id = c.id\n" +
                "where a.id=? ";
        String sql = _sql+ "order by y_team_user_type desc ";
        String[] _teamuserid = getPara("sourcekey").split("-");
        Map _re = new HashMap();
        if(_teamuserid.length>0 && "t_y_teamruser".equals(_teamuserid[0])    ){
            String teamuserid = _teamuserid[1];
            Record list = Db.findFirst(sql,NumberTool.safeToInteger(teamuserid,0));
            _re = list.getColumns();
            YTeamModel yTeamModel = YTeamModel.dao.findById(list.getInt("y_team_id"));
            _re.put("teamname", yTeamModel.getStr("y_team_name"));
            _re.put("teamid", getParaToInt(0));

        }
        renderJson(_re);
    }
    public void team() {
        String _sql = "select c.y_team_name,a.* from t_y_teamruser a\n" +
                "  LEFT JOIN t_y_team c on a.y_team_id = c.id\n" +
                "where a.y_team_id=? ";
        String sql = _sql+ "order by y_team_user_type desc ";

        List<Record> list = Db.find(sql,getParaToInt(0));
        List<Map> listmyul = new ArrayList<Map>();
        for (Record yp : list) {
            Map a = new HashMap();
            a.put("text", yp.getStr("ucenter_user_name"));
            a.put("id", "id" + yp.getInt("id"));
            listmyul.add(a);
        }
        for (int i = 1; i < 4; i++) {
            Map a = new HashMap();
            a.put("text", "&nbsp;&nbsp;&nbsp;");
            a.put("id", "id");
            listmyul.add(a);
        }
        setAttr("listmyul", listmyul);
        YTeamModel yTeamModel = YTeamModel.dao.findById(getParaToInt(0));
        setAttr("teamname",yTeamModel.getStr("y_team_name"));
        setAttr("teamid", getParaToInt(0));
        setAttr("wfidkey", getParaToInt("wfidkey"));
        UcenterUserModel ucenterUserModel =(UcenterUserModel)getAttr("user");
        setAttr("currentid", ucenterUserModel.get("id"));
        setAttr("currentname", ucenterUserModel.get("ucenter_user_name"));
        render("/WEB-INF/view/fore/y/y-team.html");
    }

    public void isay() {

        List<YIsayModel> list = YIsayModel.dao.findAll();
        List<Map> listmyul = new ArrayList<Map>();
        for (YIsayModel yp : list) {
            Map a = new HashMap();
            a.put("text", yp.getStr("y_isay_title"));
            a.put("sort", yp.getInt("id"));
            a.put("id", "id" + yp.getInt("id"));
            listmyul.add(a);
        }
        setAttr("listmyul", listmyul);
        render("/WEB-INF/view/fore/y/y-isay.html");
    }

    public void isaydetail() {

        setAttr("id", getPara("id"));
        setAttr("y_comment_srctable", "t_y_idea");
        List<Map> listmyul = new ArrayList<Map>();
        List<Map> listmyul1 = new ArrayList<Map>();

        setAttr("seevideo", JFQUtils.checkSeeVideo());
        Integer isayid = getParaToInt(0);
        setAttr("isayid", isayid);
        YIsayModel isayModel = YIsayModel.dao.findById(isayid);
        if (isayModel != null) {
            setAttr("isaytitle", isayModel.getStr("y_isay_title"));
            Map map = new HashMap();
            map.put("y_isay_id", isayid);
            List<YIsaydetailModel> isaydetailModelList = YIsaydetailModel.dao.find(null, map);
            setAttr("detaillist", isaydetailModelList);
        }
        Integer isaydetailid = getParaToInt(1);
        if (isaydetailid != null) {
            setAttr("isaydetailid", isaydetailid);
            YIsaydetailModel isaydetailModel = YIsaydetailModel.dao.findById(isaydetailid);
            if (isaydetailModel != null) {
                setAttr("isaydetailtitle", isaydetailModel.getStr("y_isaydetail_title"));
                setAttr("isaydetailcontent", isaydetailModel.getStr("y_isaydetail_content"));
                Map map = new HashMap();
                map.put("y_core_srctable", "t_y_isaydetail");
                map.put("y_core_srcid", isaydetailid);
                List<YCoreModel> coreModels = YCoreModel.dao.find(null, map);
                for (YCoreModel y : coreModels) {
                    Map a = new HashMap();
                    a.put("text", y.getStr("y_core_content"));
                    a.put("id", "id" + y.getInt("id"));
                    listmyul.add(a);
                }

            }
        }

        List<YCoreModel> yCoreModelList = YCoreModel.dao.find("select * from t_y_core a where a.y_core_srctable = 't_y_isaydetail'" +
                " and a.y_core_srcid in (select id from t_y_isaydetail b where b.y_isay_id = ?)", isayid);
        Map<String, List> coremaps = new HashMap();
        for (YCoreModel ycore : yCoreModelList) {
            List<Map> list = coremaps.get("ycore" + ycore.getInt("y_core_srcid"));
            if (list == null) {
                list = new ArrayList<Map>();
                coremaps.put("ycore" + ycore.getInt("y_core_srcid"), list);
            }
            Map a = new HashMap();
            a.put("text", ycore.getStr("y_core_content"));
            a.put("id", "id" + ycore.getInt("id"));
            list.add(a);
        }
        setAttr("maplistcore", coremaps);

        for (int i = 0; i >= -1; i--) {
            Map a = new HashMap();
            a.put("text", "&nbsp;&nbsp;&nbsp;");
            a.put("id", "id" + i);
            listmyul.add(a);
            if (i > -3) {
                a = new HashMap();
                a.put("id", "id" + i);
                a.put("text", i + "&nbsp;&nbsp;&nbsp;adfadf稍等");
                listmyul1.add(a);
            }
        }

        setAttr("listmyul", listmyul);

        //todo
        render("/WEB-INF/view/fore/y/y-isay-detail.html");
    }

    public void getcomment() {
        Map map = new HashMap();
        map.put("y_comment_srctable", getPara("y_comment_srctable"));
        map.put("y_comment_srcid", getPara("y_comment_srcid"));
        renderJson(YCommentModel.dao.find(map));
    }

    public void comment() {
        setAttr("id", getPara("y_comment_srcid"));
        setAttr("y_comment_srctable", "t_y_idea");
        Map map = new HashMap();
        map.put("y_comment_srctable", getPara("y_comment_srctable"));
        map.put("y_comment_srcid", getPara("y_comment_srcid"));
        setAttr("listcomment", YCommentModel.dao.find(map));

        render("/WEB-INF/view/fore/y/y-comment-input.html");
    }

    /**
     * 跳转到首页
     */
    public void index() {
        setAttr("qpage", list(YCommentModel.class));
        if (getPara() == null) {
            render("/WEB-INF/view/manage/y/y-comment-index.html");
        } else {
            setAttr("id", getPara("id"));
            setAttr("y_comment_srctable", "t_y_idea");
            List<Map> listmyul = new ArrayList<Map>();
            List<Map> listmyul1 = new ArrayList<Map>();
            for (int i = 0; i >= -3; i--) {
                Map a = new HashMap();
                a.put("text", "&nbsp;&nbsp;&nbsp;");
                a.put("id", "id" + i);
                listmyul.add(a);
                if (i > -3) {
                    a = new HashMap();
                    a.put("id", "id" + i);
                    a.put("text", i + "&nbsp;&nbsp;&nbsp;adfadf稍等");
                    listmyul1.add(a);
                }
            }
            setAttr("seevideo", JFQUtils.checkSeeVideo());

            setAttr("listmyul", listmyul);
            setAttr("listmyul1", listmyul1);
            render("/WEB-INF/view/fore/y/y-" + getPara() + ".html");
        }
    }

    public void wf(){
        Enumeration<String> en = getParaNames();
        while (en.hasMoreElements()) {
            String key = en.nextElement();
            setAttr(key,getPara(key));
        }
        render(getPara("url"));
    }
    public void wfready(){
        UcenterUserModel ucenterUserModel =(UcenterUserModel)getAttr("user");
        setAttr("currentid", ucenterUserModel.get("id"));
        setAttr("currentname", ucenterUserModel.get("ucenter_user_name"));

        render("/wfready.jsp");
    }

    public void wfbuilder(){
        UcenterUserModel ucenterUserModel =(UcenterUserModel)getAttr("user");
        setAttr("currentid", ucenterUserModel.get("id"));
        setAttr("currentname", ucenterUserModel.get("ucenter_user_name"));

        render("/wfbuilder.jsp");
    }

    public void autoteamcache() {
        List<Record> list = Db.find("select id as value,y_team_name as result,cuser_name as name  from t_y_team");
        renderJson(list);//通过缓存返回的
        /*try { //通过直接后台查询
            this.getResponse().setCharacterEncoding("utf-8");
            this.getResponse().getWriter().print(JsonKit.toJson(list));
        } catch (Exception e) {
            e.printStackTrace();
        }*/
    }

    public void autoteam() {
        String q = getPara("q");
        List<Record> list = Db.find("select id as value,y_team_name as result,cuser_name as name  from t_y_team where 1=1 and y_team_name like '%?%'",q);

//        renderJson(list);//通过缓存返回的
        try { //通过直接后台查询
            this.getResponse().setCharacterEncoding("utf-8");
            this.getResponse().getWriter().print(JsonKit.toJson(list));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void saveteam(){
        Integer teamid = getParaToInt("row.teamid");
        String member = getPara("row.cuser1_value");
        String member_name = getPara("row.cuser1");
        String leader = getPara("row.cuser2_value");
        String leader_name = getPara("row.cuser2");
        int i =0;
        for(String uid :member.split(",")){
            Record record = new Record();
            record.set("y_team_id",teamid);
            record.set("y_team_user_type",1);
            record.set("ucenter_user_id", NumberTool.safeToInteger(uid,0));
            record.set("ucenter_user_name",StringUtil.trimValueOf( member_name.split(",")[i++]));
            saveRecord("t_y_teamruser", record);
        }
        Record record = new Record();
        record.set("y_team_id",teamid);
        record.set("y_team_user_type",2);
        int j=0;
        for(String uid :leader.split(",")){
            record.set("ucenter_user_id", NumberTool.safeToInteger(uid,0));
            record.set("ucenter_user_name", StringUtil.trimValueOf(leader_name.split(",")[j++]));
        }
        saveRecord("t_y_teamruser", record);
        renderJson("success");
    }


    public void setteam(){
        setAttr("teamid",getPara(0));//"teamid"
        render("/WEB-INF/view/fore/y/y-team-user-set.html");
    }

    public void autouser() {
        String q = getPara("q");
        List<Record> list = Db.find("select id as value,ucenter_user_name as result,ucenter_user_name as name  from t_ucenter_user where 1=1 and ucenter_user_name like '%?%'",q);
        //renderJson(list);//通过缓存返回的
        try { //通过直接后台查询
            this.getResponse().setCharacterEncoding("utf-8");
            this.getResponse().getWriter().print(JsonKit.toJson(list));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void autousercache() {
        List<Record> list = Db.find("select id as value,ucenter_user_name as result,ucenter_user_name as name  from t_ucenter_user where 1=1");
        renderJson(list);//通过缓存返回的
        /*try { //通过直接后台查询
            this.getResponse().setCharacterEncoding("utf-8");
            this.getResponse().getWriter().print(JsonKit.toJson(list));
        } catch (Exception e) {
            e.printStackTrace();
        }*/
    }

    public void getAutoUser(){
        List<Record> list = Db.find("select ucenter_user_id ,ucenter_user_name,y_team_user_type from t_y_teamruser where 1=1 and y_team_id = ?",getParaToInt("teamid"));
        Object[] membernames = RecordUtil.JsontoArrayFilter(list,"ucenter_user_name","y_team_user_type",1);
        Object[] memberids = RecordUtil.JsontoArrayFilter(list,"ucenter_user_id","y_team_user_type",1);
        Object[] leadernames = RecordUtil.JsontoArrayFilter(list,"ucenter_user_name","y_team_user_type",2);
        Object[] leaderidss = RecordUtil.JsontoArrayFilter(list,"ucenter_user_id","y_team_user_type",2);
        Map result = new HashMap();
        result.put("membernames",membernames);
        result.put("memberids",memberids);
        result.put("leadernames",leadernames);
        result.put("leaderids",leaderidss);
        renderJson(result);
    }

    /**
     *
     */
    public void getobj() {
        String _table = getPara(0);
        try {
            Class cls = Class.forName(pertab + StringUtil.toLowerCaseTwoChar(_table) + endtab);//加载UserBean类到内存中！获取一个Class对象
            renderJson(getRow(cls));
        } catch (Exception e) {
            Logger.getLogger(this.getClass()).error("保存报错" + _table, e);
        }
    }

    public void dely() {
        String _table = getPara(0);
        Integer _id = null;
        try {
            Class cls = Class.forName(pertab + StringUtil.toLowerCaseTwoChar(_table) + endtab);//加载UserBean类到内存中！获取一个Class对象
            del(cls);
        } catch (Exception e) {
            Logger.getLogger(this.getClass()).error("保存报错" + _table, e);
        }
        Logger.getLogger(this.getClass()).info("保存成功" + _table);
        Map json = new HashMap();
        json.put("success", "yes");
        renderJson(json);
    }

    public void savey() {
        String _model = getPara(0);
        Object _obj = null;
        try {
            Class cls = Class.forName(pertab + StringUtil.toLowerCaseTwoChar(_model) + endtab);//加载UserBean类到内存中！获取一个Class对象
            _obj = save(cls);
        } catch (Exception e) {
            Logger.getLogger(this.getClass()).error("保存报错" + _model, e);
        }
        Logger.getLogger(this.getClass()).info("保存成功" + _model);
        renderJson(_obj);
    }

    public void findy() {
        String _model = getPara(0);
        Integer _id = null;
        try {
            Class cls = Class.forName(pertab + StringUtil.toLowerCaseTwoChar(_model) + endtab);//加载UserBean类到内存中！获取一个Class对象
            Object obj = cls.newInstance();//通过class类反射一个对象实体！
            Model m = (Model) getModel(obj.getClass());
            renderJson(m.findById(getParaToInt("row.id")).toJson());
        } catch (Exception e) {
            Logger.getLogger(this.getClass()).error("保存报错" + _model, e);
        }
        Logger.getLogger(this.getClass()).info("保存成功" + _model);
    }


    /**
     * 跳转到保存修改页
     */
    public void savep() {
        setAttr("row", getRow(YCommentModel.class));
        render("/WEB-INF/view/manage/y/y-comment-input.html");
    }

    /**
     * 保存或修改
     */
    public void save() {
        String validate = validate();
        if (validate == null) {
            renderJson(save(YCommentModel.class));
        } else {
            renderJson(QJsonUtil.error(validate));
        }
    }

    /**
     * 删除一条或多条
     */
    public void del() {
        renderJson(del(YCommentModel.class));
    }

}
